#!/bin/bash
domain=com.example
ndk="$HOME/android/android-ndk-r5b"
sdk="$HOME/android/android-sdk-mac_x86"
root="$ndk/toolchains/arm-linux-androideabi-4.4.3/prebuilt/darwin-x86/bin/arm-linux-androideabi"
common="$root-gcc"
commonflags="-ffunction-sections -fdata-sections -fvisibility=default -Bdynamic -shared --sysroot=$ndk/platforms/android-9/arch-arm"
cppflags="-I$ndk/platforms/android-9/arch-arm/usr/include -I$ndk/sources/android/native_app_glue/  -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__ -DANDROID -DSK_RELEASE"
ldflags="$commonflags -L$ndk/platforms/android-9/arch-arm/usr/lib -Wl,--no-undefined -Wl,-z,noexecstack"
ar="$root-ar"
ccflags="-Wall -fpic -ffunction-sections -funwind-tables -fstack-protector -Wno-psabi -march=armv5te -mtune=xscale -msoft-float -fno-strict-aliasing -finline-limit=64   -Wa,--noexecstack "
cc="$common $commonflags $ccflags $cppflags"
ld="$common $commonflags $ldflags"

log() {
    echo $* 1>&2
}

builddir() {
    echo "b"
}

pkgdir() {
    echo `builddir`/$1.plugin
}

condir() {
    echo `pkgdir $1`
}

resdir() {
    echo `condir $1`
}

bindir() {
    echo `condir $1`
}

obj() {
    log "compiling $*"
    dst=`builddir`/$1.o
    shift
    $cc -c -I src -o $dst $*
    echo $dst
}

exe() {
    log "linking $*"
    name=$1
    shift
    obj=$1
    shift
    dst=`builddir`/lib$name.so
    log $ld -shared -o $dst $obj -Wl,-soname,lib$name.so -L `builddir` $* -llog -landroid -lEGL -lGLESv1_CM -lGLESv2 -lc -lm -lsupc++ 
    $ld -shared -o $dst $obj -Wl,-soname,lib$name.so -L `builddir` $* -llog -landroid -lEGL -lGLESv1_CM -lGLESv2 -lc -lm -ldl -lsupc++
    echo $dst
}

pkg() {
    log "packaging $*"
    name=$1
    exe=$2
    pkgdir=`builddir`/$name
    dstdir=$pkgdir/libs/armeabi
    bindir=$pkgdir/bin
    apk=$bindir/$name-debug.apk
    install -d $dstdir
    install -d $bindir
    cp $exe $dstdir
    sed s/NAME/$name/g templates/android/AndroidManifest.xml | sed s/DOMAIN/$domain/g > $pkgdir/AndroidManifest.xml
    $sdk/tools/android update project -p $pkgdir -t 1 > /dev/null
    ant debug -f $pkgdir/build.xml > /dev/null
    mv $bindir/NativeActivity-debug.apk $apk
    echo $apk
}

ins() {
    name=$1
    apk=$2
    $sdk/platform-tools/adb uninstall $domain.$name
    $sdk/platform-tools/adb install $apk    
}

rm -fR `builddir`
install -d `builddir`
cvobjs="`obj android src/android.c` \
`obj glue $ndk/sources/android/native_app_glue/android_native_app_glue.c`"
testobj=`obj test test/test.c`
testexe=`exe test $testobj $cvobjs`
testpkg=`pkg test $testexe`
itestpkg=`ins test $testpkg`
